<template>
  <div class="container">
    <!-- 左侧美化区域 -->
    <div class="left-panel">
      <div class="welcome-content">
        <h1>欢迎注册管理系统</h1>
        <p>高效 · 安全 · 智能</p>
        <div class="decor-circle decor1"></div>
        <div class="decor-circle decor2"></div>
      </div>
    </div>
    <!-- 右侧注册框 -->
    <div class="reg-form">
      <div class="form-container">
        <h1>注册账号</h1>
        <el-form
          ref="formRef"
          :rules="rules"
          :model="postUser"
          label-width="85px"
        >
          <el-form-item label="注册邮箱:" prop="user_email">
            <el-input v-model="postUser.user_email"></el-input>
          </el-form-item>
          <el-form-item label="用户名:" prop="username">
            <el-input v-model="postUser.username"></el-input>
          </el-form-item>
          <el-form-item label="密码:" prop="user_password">
            <el-input
              type="password"
              v-model="postUser.user_password"
            ></el-input>
          </el-form-item>
          <el-form-item label="确认密码:" prop="user_repassword">
            <el-input
              type="password"
              v-model="postUser.user_repassword"
            ></el-input>
          </el-form-item>
          <el-form-item label="验证码:" prop="reg_code">
            <div class="code-row">
              <el-input class="el-input-code"
                type="text"
                :disabled="isInputDisabled"
                v-model="postUser.reg_code"
              ></el-input>
              <el-button
                type="primary"
                :disabled="isButtonDisabled"
                @click="sendClickRegCode"
                >{{ buttonText }}</el-button
              >
            </div>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="validateForm">注册</el-button>
            <el-button type="success" @click="backLogin">返回</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onBeforeUnmount } from "vue";
import { useRouter } from "vue-router";
import { sendRegCode, regUser } from "@/api";
import { ElMessage } from "element-plus";

const router = useRouter();

const postUser = ref({
  username: "",
  user_email: "",
  user_password: "",
  user_repassword: "",
  reg_code: "",
});

const postRegCode = ref({
  user_email: "",
});

const isInputDisabled = ref(true);  //默认注册码输入框不可用
const isButtonDisabled = ref(false); //默认发送注册码按钮可用
const count = ref(60);
const timeRunning = ref(false);
const timer = ref(null);
const buttonText = ref("发送验证码");

// Move validatePass here to ensure it's initialized before use
const validatePass = (rule, value) => {
  if (value !== postUser.value.user_password) {
    return Promise.reject("两次输入密码不一致");
  } else {
    return Promise.resolve();
  }
};

const validateEmail2 = (rule, value) => {
  const regex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
  if (regex.test(postUser.value.user_email)) {
    return Promise.resolve();
  } else {
    return Promise.reject("请输入有效的邮箱地址");    
  }
};

const rules = ref({
  user_email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    { validator: validateEmail2, trigger: "blur" },
  ],
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 3, max: 15, message: "长度再3到15个字符", trigger: "blur" },
  ],
  user_password: [{ required: true, message: "请输入密码", trigger: "blur" }],
  user_repassword: [
    { required: true, message: "请输入密码确认", trigger: "blur" },
    { validator: validatePass, trigger: "blur" },
  ],
  reg_code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
});

const formRef = ref(null);

const sendClickRegCode = async () => {
  if (validateEmail()) {
    // await sendCodeHandler();    //异步请求时打开该方法
    isInputDisabled.value = false;
    isButtonDisabled.value = true;
    startCount();
  }
};

const sendCodeHandler = async () => {
  let res = await sendRegCode(postUser.value);
  if (res.code == 200) {
    ElMessage({
      message: res.msg,
      type: "success",
    });
  } else {
    ElMessage.error(res.msg);
  }
};

const validateEmail = () => {
  const regex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
  if (regex.test(postUser.value.user_email)) {
    return true;
  } else {
    ElMessage.error("请输入有效的邮箱地址");
    return false;
  }
};

const startCount = () => {
  timeRunning.value = true;
  timer.value = setInterval(() => {
    if (count.value > 0) {
      buttonText.value = `请稍后${count.value}秒`;
      count.value--;
    } else {
      stopCountdown();
      buttonText.value = "发送验证码";
      isButtonDisabled.value = false;
    }
  }, 1000);
};

const stopCountdown = () => {
  clearInterval(timer.value);
  count.value = 60;
  timeRunning.value = false;
};

const validateForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      // regClickUser();  //异步注册时打开该方法
    }
  });
};

const regClickUser = async () => {
  let res = await regUser(postUser.value);
  if (res.code == 200) {
    ElMessage({
      message: res.msg,
      type: "success",
    });
    router.push("./login");
  } else {
    ElMessage.error(res.msg);
  }
};

const backLogin = () => {
  router.push("./login");
};

onBeforeUnmount(() => {
  if (timer.value) {
    clearInterval(timer.value);
  }
});
</script>

<style lang="scss" scoped>
.container {
  display: flex;
  height: 100vh;
  width: 100vw;
  background-color: #f8f9fa;

  .left-panel {
    flex: 1 1 50%;
    height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    background: linear-gradient(135deg, #6a82fb 0%, #fc5c7d 100%);
    position: relative;
    min-width: 350px;

    .welcome-content {
      color: #fff;
      text-align: center;
      z-index: 2;
      position: relative;

      h1 {
        font-size: 2.5rem;
        font-weight: bold;
        margin-bottom: 1rem;
        letter-spacing: 2px;
        text-shadow: 0 2px 8px rgba(0,0,0,0.15);
      }
      p {
        font-size: 1.2rem;
        opacity: 0.9;
        margin-bottom: 2rem;
      }
    }

    .decor-circle {
      position: absolute;
      border-radius: 50%;
      opacity: 0.18;
      z-index: 1;
    }
    .decor1 {
      width: 180px;
      height: 180px;
      left: 10%;
      top: 20%;
      background: #fff;
      filter: blur(2px);
    }
    .decor2 {
      width: 120px;
      height: 120px;
      right: 12%;
      bottom: 18%;
      background: #fff;
      filter: blur(1px);
    }
  }

  .reg-form {
    flex: 1 1 50%;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: rgba(255, 255, 255, 0.95);

    .form-container {
      width: 400px;
      padding: 45px;
      background: white;
      border-radius: 16px;
      box-shadow: 0 8px 32px rgba(0, 0, 0, 0.08);
      transition: transform 0.3s ease;
      display: flex;
      flex-direction: column;
      align-items: center;
    }

    .form-container:hover {
      transform: translateY(-5px);
    }

    .form-container h1 {
      text-align: center;
      margin-bottom: 40px;
      color: #2c3e50;
      font-weight: 600;
    }

    :deep(.el-input) {
      margin-bottom: 24px;
      width: 100%;
      min-width: 220px;
      max-width: 320px;
    }

    :deep(.el-input__inner) {
      height: 48px;
      border-radius: 8px;
      font-size: 17px;
    }

    // 移除 el-form-item__content 的 margin-left
    :deep(.el-form-item__content) {
      margin-left: 0 !important;
    }

    .code-row {
      display: flex;
      align-items: stretch; // 关键：让子项高度一致
      width: 100%;
      min-width: 220px;
      max-width: 320px;
      gap: 0;
    }

    .el-input-code {
      flex: 1 1 auto;
      min-width: 0;
      margin-right: 0;
      display: flex;
      align-items: stretch;
      :deep(.el-input__wrapper),
      :deep(.el-input__inner) {
        height: 48px !important;
        border-radius: 8px 0 0 8px;
        font-size: 17px;
        display: flex;
        align-items: center;
      }
    }

    .el-button {
      flex: 0 0 auto;
      width: 110px;
      min-width: 90px;
      height: 50px;
      font-size: 15px;
      border-radius: 0 8px 8px 0;
      margin-left: 0;
      margin-right: 0;
      border-left: none;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 0;
    }

    /* 简洁美化注册和返回按钮，并两端对齐 */
    :deep(.el-form-item:last-child) {
      display: flex !important;
      justify-content: space-between !important;
      width: 100%;
      max-width: 320px;
      margin: 0 auto;
      padding: 0;
    }
    :deep(.el-form-item:last-child) .el-button {
      flex: 1 1 0;
      height: 44px;
      margin: 0;
      border-radius: 8px;
      font-size: 16px;
      font-weight: 500;
      box-shadow: none;
      border: 1px solid #e0e3e7;
      background: #f7f8fa;
      color: #333;
      transition: background 0.2s, color 0.2s, border 0.2s;
      min-width: 0;
    }
    :deep(.el-form-item:last-child) .el-button:first-child {
      margin-right: 8px;
    }
    :deep(.el-form-item:last-child) .el-button--primary {
      background: #6a82fb;
      color: #fff;
      border: 1px solid #6a82fb;
    }
    :deep(.el-form-item:last-child) .el-button--primary:hover {
      background: #4e6efb;
      border: 1px solid #4e6efb;
      color: #fff;
    }
    :deep(.el-form-item:last-child) .el-button--success {
      background: #43e97b;
      color: #fff;
      border: 1px solid #43e97b;
    }
    :deep(.el-form-item:last-child) .el-button--success:hover {
      background: #2ec97b;
      border: 1px solid #2ec97b;
      color: #fff;
    }
    :deep(.el-form-item:last-child) .el-button:active {
      transform: scale(0.98);
    }
  }

  @media (max-width: 900px) {
    flex-direction: column;
    .left-panel {
      min-height: 180px;
      height: 220px;
      min-width: unset;
      border-radius: 0 0 32px 32px;
    }
    .reg-form {
      margin: 30px 0;
    }
  }
}
</style>
